import axios from "axios"
import { showLoadingToast,closeToast,showFailToast,showConfirmDialog } from 'vant'
import 'vant/es/toast/style'
import 'vant/es/dialog/style'
import 'vant/es/notify/style'
import 'vant/es/image-preview/style'
import store from '@/store'
import router from "@/router";

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
})

//前置拦截
service.interceptors.request.use(config => {
    //打开加载中效果
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
    })

    //请求头增加token
    if(store.getters.token){
        config.headers['token'] = store.getters.token
    }

    return config

},error => {
    return Promise.reject(error)
})

//后置拦截
service.interceptors.response.use(response => {
    //状态码为200的处理
    //1、关闭加载中效果
    closeToast()
    //2、拿到结果
    const result = response.data

    if(result.code === 200){
        return result
    }else if(result.code === 401){
        //调用store里面的logout方法清除token和userInfo
        store.dispatch('logout')

        //弹窗：请登录后操作（取消、去登录）
        showConfirmDialog({
            message: '请登录后操作',
            confirmButtonText: '去登录'
        }).then(() => {
            // on confirm
            router.push({
                path: '/login',
                query: {
                    redirect: router.currentRoute.value.fullPath//为了登录后跳回来
                }
            })
        }).catch(() => {
            // on cancel
        });
    }else {
        showFailToast(result.message)
        return Promise.reject(new Error(result.message))
    }
},error => {
    //状态码非200的处理
    //1、关闭加载中效果
    closeToast()
    //2、提示报错信息
    let {status,data} = error.response
    showFailToast(data.message)
})

export default service
